package com.github.caijh.mall.store.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.caijh.commons.util.Asserts;
import com.github.caijh.commons.util.Collections;
import com.github.caijh.framework.core.exception.BizException;
import com.github.caijh.framework.web.controller.BaseController;
import com.github.caijh.mall.common.CommonResult;
import com.github.caijh.mall.common.MessageConstants;
import com.github.caijh.mall.store.model.StoreProduct;
import com.github.caijh.mall.store.request.StoreProductAttrValueRequest;
import com.github.caijh.mall.store.request.StoreProductReqBody;
import com.github.caijh.mall.store.request.StoreProductSearchReqBody;
import com.github.caijh.mall.store.request.StoreProductStockRequest;
import com.github.caijh.mall.store.response.StoreProductTabsHeader;
import com.github.caijh.mall.store.response.StoreProductVo;
import com.github.caijh.mall.store.service.StoreCartService;
import com.github.caijh.mall.store.service.StoreProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/admin/store/product")
@Api(tags = "商品")
public class StoreProductController extends BaseController {

    @Inject
    private StoreProductService storeProductService;

    @Inject
    private StoreCartService storeCartService;

    /**
     * 分页显示商品表
     *
     * @param reqBody 搜索条件
     * @return Page
     */
    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/list")
    public IPage<StoreProductVo> page(
            @RequestBody @Validated StoreProductSearchReqBody reqBody) {
        return storeProductService.page(reqBody, reqBody.getPageParams());
    }

    /**
     * 新增商品表
     *
     * @param storeProductReqBody 新增参数
     */
    @ApiOperation(value = "新增")
    @PostMapping(value = "/save")
    public void save(@RequestBody @Validated StoreProductReqBody storeProductReqBody) {
        checkProductAttrValuePrice(storeProductReqBody);
        storeProductService.save(storeProductReqBody);
    }

    private void checkProductAttrValuePrice(StoreProductReqBody storeProductReqBody) {
        List<StoreProductAttrValueRequest> attrValues = storeProductReqBody.getAttrValue();
        if (Collections.isNotEmpty(attrValues)) {
            for (StoreProductAttrValueRequest attr : attrValues) {
                Asserts.isTrue(attr.getPrice().compareTo(BigDecimal.ZERO) >= 0, () -> BizException.of(MessageConstants.PRODUCT_PRICE_ERROR));
            }
        }
    }

    /**
     * 删除商品表
     *
     * @param id   商品id
     * @param type 商品的状态
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "删除")
    @GetMapping(value = "/delete/{id}")
    public void delete(@RequestBody @PathVariable Integer id, @RequestParam(value = "type", required = false, defaultValue = "recycle") String type) {
        if (storeProductService.deleteProduct(id, type)) {
            storeCartService.productStatusNotEnable(id);
        }
    }

    /**
     * 恢复已删除商品表
     *
     * @param id Integer
     * @author Stivepeim
     * @since 2020-08-28
     */
    @ApiOperation(value = "恢复商品")
    @GetMapping(value = "/restore/{id}")
    public void restore(@RequestBody @PathVariable Integer id) {
        storeProductService.reStoreProduct(id);
    }

    /**
     * 修改商品表
     *
     * @param storeProductReqBody 修改参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "修改")
    @PostMapping(value = "/update")
    public void update(@RequestBody @Validated StoreProductReqBody storeProductReqBody) {
        this.checkProductAttrValuePrice(storeProductReqBody);
        storeProductService.update(storeProductReqBody);
    }

    /**
     * 查询商品表信息
     *
     * @param id Integer
     * @return StoreProductResponse
     */
    @ApiOperation(value = "详情")
    @GetMapping(value = "/info/{id}")
    public StoreProductVo info(@PathVariable Integer id) {
        return storeProductService.getByProductId(id);
    }

    /**
     * 商品tabs表头数据
     *
     * @return {@code List<StoreProductTabsHeader>}
     */
    @ApiOperation(value = "商品表头数量")
    @GetMapping(value = "/tabs/headers")
    public List<StoreProductTabsHeader> getTabsHeader() {
        return storeProductService.getTabsHeader();
    }


    /**
     * 上架
     *
     * @param id integer id
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @ApiOperation(value = "上架")
    @GetMapping(value = "/putOnShell/{id}")
    public void putOn(@PathVariable Integer id) {
        StoreProduct storeProduct = new StoreProduct();
        storeProduct.setId(id);
        storeProduct.setIsShow(true);
        storeProductService.updateById(storeProduct);
    }

    /**
     * 下架
     *
     * @param id integer id
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @ApiOperation(value = "下架")
    @GetMapping(value = "/offShell/{id}")
    public void offShell(@PathVariable Integer id) {
        StoreProduct storeProduct = storeProductService.getById(id);
        storeProduct.setIsShow(false);
        storeProductService.updateById(storeProduct);
        storeCartService.productStatusNotEnable(id);
    }

    /**
     * 虚拟销量
     *
     * @param id  商品id
     * @param num 虚拟销量
     */
    @ApiOperation(value = "虚拟销量")
    @GetMapping(value = "/ficti/{id}/{num}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataTypeClass = Integer.class, required = true),
            @ApiImplicitParam(name = "num", value = "数值", dataTypeClass = Integer.class, required = true),
    })
    public void sale(@PathVariable Integer id, @PathVariable Integer num) {
        StoreProduct storeProduct = storeProductService.getById(id);
        storeProduct.setFicti(num);
        storeProductService.updateById(storeProduct);
    }

    /**
     * 库存变动
     *
     * @param request StoreProductStockRequest 参数
     * @author Mr.Zhang
     * @since 2020-05-19
     */
    @ApiOperation(value = "库存变动")
    @GetMapping(value = "/stock")
    public void stock(@Validated StoreProductStockRequest request) {
        storeProductService.stockAddRedis(request);
    }

    @ApiOperation(value = "导入99Api商品")
    @PostMapping(value = "/importProduct")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "form", value = "导入平台1=淘宝，2=京东，3=苏宁，4=拼多多, 5=天猫", dataTypeClass = Integer.class, required = true),
            @ApiImplicitParam(name = "url", value = "URL", dataTypeClass = String.class, required = true),
    })
    public CommonResult<StoreProductReqBody> importProduct(
            @RequestParam @Valid int form,
            @RequestParam @Valid String url) throws IOException, JSONException {
        StoreProductReqBody productRequest = storeProductService.importProductFromUrl(url, form);
        return CommonResult.success(productRequest);
    }

    /**
     * 获取复制商品配置
     *
     * @return map
     */
    @ApiOperation(value = "获取复制商品配置")
    @PostMapping(value = "/copy/config")
    public CommonResult<Map<String, Object>> copyConfig() {
        return CommonResult.success(storeProductService.copyConfig());
    }

    @ApiOperation(value = "复制平台商品")
    @PostMapping(value = "/copy/product")
    @ApiImplicitParam(name = "url", value = "URL", dataTypeClass = String.class, required = true)
    public CommonResult<Map<String, Object>> copyProduct(@RequestParam @Valid String url) {
        return CommonResult.success(storeProductService.copyProduct(url));
    }

}



